package backend.service.base;

import backend.model.base.DBModel;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

@Repository(value = "DBModelDao")
public class DBModelDaoImpl<DBM extends DBModel> extends HibernateDaoSupport implements DBModelDao<DBM> {

	@Autowired
	public DBModelDaoImpl(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
	}

    @Override
    public DBM getById(Class<DBM> entityClass, int id) {
        return getHibernateTemplate().get(entityClass, id);
    }

    @Override
    public void saveOrUpdate(DBM dbModel) {
		getHibernateTemplate().saveOrUpdate(dbModel);
	}

    @Override
    public void bulkSaveOrUpdate(Collection<DBM> dbModelCollection) {
        getHibernateTemplate().saveOrUpdateAll(dbModelCollection);
    }

    @Override
    public void save(DBM dbModel) {
        getHibernateTemplate().save(dbModel);
    }

    @Override
    public void bulkSave(Collection<DBM> dbModelCollection) {
        getHibernateTemplate().saveOrUpdateAll(dbModelCollection);
    }

    @Override
    public void update(DBM dbModel) {
        getHibernateTemplate().update(dbModel);
    }

    @Override
    public void delete(DBM dbModel) {
		getHibernateTemplate().delete(dbModel);
	}

    @Override
    public void bulkDelete(Collection<DBM> dbModelCollection) {
        getHibernateTemplate().deleteAll(dbModelCollection);
    }

    @Override
    public List<DBM> findByNamedQuery(String queryName) {
        return getHibernateTemplate().findByNamedQuery(queryName);
    }

    @Override
    public List<DBM> findByNamedQueryAndParams(String queryName, String[] paramNames, Object[] paramValues) {
        return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, paramValues);
    }

    public DBM findSingleResultByCriteria(DetachedCriteria criteria) {
        List list = getHibernateTemplate().findByCriteria(criteria, 0, 1);
        if (list.size() > 0) {
            return (DBM) list.get(0);
        }
        return null;
    }
}